package com.spukmk3me.impl.libgdx;

import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputProcessor;
import com.spukmk3me.io.userinput.ButtonInput;

public class LibgdxButtonInput extends ButtonInput implements InputProcessor
{
    public LibgdxButtonInput()
    {
        m_tcBuffer = new char[ TC_BUFFER_LENGTH ];
        m_tcBufferFirst = m_tcBufferLength = 0;
    }
    
    @Override
    public boolean keyDown( int keycode )
    {
        switch ( keycode )
        {
            case Keys.BACK:
            case Keys.BACKSPACE:
                applyPressData( KC_BACK, true );
                break;
        }
        
        return true;
    }

    @Override
    public boolean keyUp( int keycode )
    {
        switch ( keycode )
        {
            case Keys.BACK:
            case Keys.BACKSPACE:
                applyPressData( KC_BACK, false );
                break;
        }

        return true;
    }

    @Override
    public boolean keyTyped( char c )
    {
        m_tcBuffer[ (m_tcBufferFirst + m_tcBufferLength) % TC_BUFFER_LENGTH ] = c;
        
        if ( m_tcBufferLength == TC_BUFFER_LENGTH )
        {
            m_tcBufferFirst++;
            m_tcBufferFirst %= TC_BUFFER_LENGTH;
        }
        else
            m_tcBufferLength++;
            
        return true;
    }
    
    @Override
    public boolean hasTypedChar()
    {
        return m_tcBufferLength != 0;
    }
    
    @Override
    public char nextTypedChar()
    {
        if ( m_tcBufferLength == 0 )
            return 0;
        
        char c = m_tcBuffer[ m_tcBufferFirst ];
        
        ++m_tcBufferFirst;
        --m_tcBufferLength;
        m_tcBufferFirst %= TC_BUFFER_LENGTH;
        
        return c;
    }

    @Override
    public boolean touchDown( int x, int y, int pointer, int button )
    {
        return false;
    }

    @Override
    public boolean touchUp( int x, int y, int pointer, int button )
    {
        return false;
    }

    @Override
    public boolean touchDragged( int x, int y, int pointer )
    {
        return false;
    }

    @Override
    public boolean mouseMoved( int x, int y )
    {
        return false;
    }

    @Override
    public boolean scrolled( int amount )
    {
        return false;
    }
    
    public static final int KC_BACK = 0x00000001;
    
    private static final int TC_BUFFER_LENGTH = 16;
    
    private char[]  m_tcBuffer;
    private int     m_tcBufferFirst, m_tcBufferLength;
}
